import axios from 'axios'
import { baseOption, API_HOST, contentTypeMap } from './base'
import router from '../router';

const service = axios.create({
    // axios中请求配置有baseURL选项，表示请求URL公共部分
    baseURL: API_HOST,
    // 超时
    timeout: 10000
})

let headers = {}

// request拦截器
service.interceptors.request.use(config => {

    const { isHasToken, contentType } = headers;
    // 让每个请求携带自定义token 
    if (isHasToken) {
        config.headers['Authorization'] = localStorage.getItem("tzxyzhdjtoken") || ""
    }

    config.headers['Content-Type'] = contentType;

    // 请求映射params参数
    if (config.params) {
        let url = config.url + '?' + tansParams(config.params);
        url = url.slice(0, -1);
        config.params = {};
        config.url = url;
    }
    return config
}, error => {
    Promise.reject(error)
})


// 响应拦截器
service.interceptors.response.use(res => {
    const { status, error } = res.data
    // 未设置状态码则默认成功状态
    const code = status || 200;

    // 二进制数据则直接返回
    if (res.request.responseType === 'blob' || res.request.responseType === 'arraybuffer') {
        return res.data
    }

    if (code === 200) {
        return Promise.resolve(res.data)
    } else {
        return Promise.reject(res.data)
    }
},
    error => {
        let { message } = error, msg = "";
        if (message == "Network Error") {
            msg = "后端接口连接异常";
        }
        else if (message.includes("timeout")) {
            msg = "系统接口请求超时";
        } else if (message.includes("401")) {
            router.push("/")
        }
        else if (message.includes("Request failed with status code")) {
            msg = "系统接口" + message.substr(message.length - 3) + "异常";
        }
        return Promise.reject({ message: msg })
    }
)

/**
 * @description 统一请求接口
 * option 参数里的属性
 * @param {string} reqUrl 请求地址 - 默认("") - (必填)
 * @param {string} reqContentType 请求头类型 JSON: json格式 FORM: form格式 FORMDATA:formData格式 - 默认(JSON)
 * @param {string} reqType 请求方式 - 默认(post) - (选填)
 * @param {object} data 请求数据 - 默认({}) - (必填)
 * @param {boolean} isUrlValue 把请求参数的id拼接到url请求里 - 默认(false) - (选填)
 * @param {boolean} isHasToken 是否请求带token - 默认(true) - (选填)
 */
export function fetchEndpoint(option) {
    // 合并参数
    let newOption = {
        ...baseOption,
        ...option
    }

    const { reqUrl, data, reqContentType, reqType, isUrlValue, isHasToken } = newOption;

    let url = isUrlValue ? `${reqUrl}/${data.id}` : reqUrl,
        reqData = {
            method: reqType,
            url,
        },
        isBody = reqContentType.toString().toUpperCase() !== 'FORM';

    headers = {
        isHasToken,
        contentType: contentTypeMap[reqContentType.toString().toUpperCase()] || "application/json; charset=utf-8"
    }

    if (isBody) {
        reqData.data = isUrlValue ? {} : data
    } else {
        reqData.params = data
    }
    return service(reqData)
}


/**
* @description 参数处理
* @param {*} params  参数
*/
export function tansParams(params) {
    let result = ''
    for (const propName of Object.keys(params)) {
        const value = params[propName];
        var part = encodeURIComponent(propName) + "=";
        if (value !== null && typeof (value) !== "undefined") {
            if (typeof value === 'object') {
                for (const key of Object.keys(value)) {
                    if (value[key] !== null && typeof (value[key]) !== 'undefined') {
                        let params = propName + '[' + key + ']';
                        var subPart = encodeURIComponent(params) + "=";
                        result += subPart + encodeURIComponent(value[key]) + "&";
                    }
                }
            } else {
                result += part + encodeURIComponent(value) + "&";
            }
        }
    }
    return result
}